package com.cfec.ipoth_service.util;

import okhttp3.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class OkHttpExampleUtil {
    /**
     * GetKIMI
     * @param url kimiAI的请求地址
     * @return 请求结果
     */
    public ResultData<Object> GetKIMI(String url) throws JSONException {
//        OkHttpClient client = new OkHttpClient();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        // 要发送的 JSON 数据
        JSONObject json = new JSONObject();
        json.put("url", url);

        // 构造 JSON 请求体
        RequestBody body = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url("http://192.168.37.97:5001/item") // 修改为你的 IP+端口
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
//                System.out.println("Response: " + response.body().string());
                String responseBody = response.body().string();
                JSONObject reponseJSON = new JSONObject(responseBody);
                String result = reponseJSON.getString("result");
                return new ResultData<>(200, "GetKIMI请求成功", result);
            } else {
                System.out.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ResultData<>(500, "GetKIMI请求失败", null);
    }
}